﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using CARMSBusiness;
using CARMSBusiness.InterFace;
using CARMSData.CollectionClasses;
using CARMSData.EntityClasses;
using CARMSData.HelperClasses;

namespace CARMS.Report
{
    [Function("Report.GeneralReport")]
    public partial class ViewReport : PageBase
    {
        private int CurrentReportCategoryID
        {
            get
            {
                return GetIntByParameter("ReportCategoryID");
            }
        }


        private int CurrentReportHeaderID
        {
            get
            {
                if (ViewState["ReportHeaderID"] == null)
                {
                    ViewState["ReportHeaderID"] = GetIntByParameter("ReportHeaderID");
                }
                return (int)ViewState["ReportHeaderID"];
            }
            set
            {
                ViewState["ReportHeaderID"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                SetButtonEnabled();
                LoadMonitor();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            GenerateItems();
            base.OnInit(e);
        }



        /// <summary>
        /// Generate column 同时保存client id 到value 中
        /// </summary>
        private void GenerateItems()
        {
            var reportCategoryEntity = new ReportCategoryEntity(CurrentReportCategoryID);
            if (!reportCategoryEntity.IsNew)
            {
                int intColspan = 0;
                TableRow newrow = new TableRow();

                foreach (ReportPropertyEntity ReportProperty in reportCategoryEntity.ReportProperty.OrderBy(x => x.SortIndex))
                {

                    //if (ReportProperty.PropertyType == DictionaryCategoryConst.GridColumnType.RelativeTable)
                    //{
                    //    if (intColspan == 4 || ReportProperty.Colspan == 4)   //保存旧的行列,另起一行
                    //    {
                    //        tableMain.Rows.Add(newrow);
                    //        intColspan = 0;
                    //        newrow = new TableRow();

                    //    }

                    //    //----------------------------------------------------在远table中 添加 company 及详细信息


                    //    //添加基本字段 
                    //    TableCell newCellTitle = new TableCell
                    //    {
                    //        ColumnSpan = 1,
                    //    };  //添加cell 
                    //    Label labelTitle = new Label()
                    //    {
                    //        Text = ReportProperty.Title,
                    //        SkinID = "LabelTitle",
                    //    };
                    //    newCellTitle.Controls.Add(labelTitle);
                    //    newrow.Cells.Add(newCellTitle);


                    //    TableCell newCellContent = new TableCell
                    //    {
                    //        ColumnSpan = (ReportProperty.Colspan > 1 ? ReportProperty.Colspan - 1 : 1),
                    //    };  //添加cell 

                    //    var dplContent = new DropDownList()
                    //    {
                    //        ID = ReportProperty.PropertyName,
                    //    };
                    //    //ControlHelper.BindListByTableName(dplContent, ReportProperty.RelativeTable, EmptyType.PleaseSelect);
                    //    //dplContent.Attributes["PropertyId"] = ReportProperty.PropertyId.ToString();
                    //    newCellContent.Controls.Add(dplContent);
                    //    newrow.Cells.Add(newCellContent); 
                    //    tableMain.Rows.Add(newrow); 
                    //    intColspan += 2;
                    //}



                    if (ReportProperty.PropertyType == DictionaryCategoryConst.GridColumnType.Title)
                    {

                        if (newrow.Cells.Count > 0)   //保存旧的行列,另起一行
                        {
                            tableMain.Rows.Add(newrow);
                        }
                        newrow = new TableRow();
                        intColspan = 0;
                        TableCell newcell1 = new TableCell
                        {
                            ColumnSpan = ReportProperty.Colspan,
                            HorizontalAlign = HorizontalAlign.Left
                        };  //添加cell 


                        Label labelTitle = new Label()
                        {
                            Text = ReportProperty.Title,
                            SkinID = "LabelTitleBlue",
                        };
                        newcell1.Controls.Add(labelTitle);


                        newrow.Cells.Add(newcell1);
                        tableMain.Rows.Add(newrow);
                        newrow = new TableRow();
                    }

                    if (ReportProperty.PropertyType == DictionaryCategoryConst.GridColumnType.TextMode)
                    {
                        if (intColspan == 4 || ReportProperty.Colspan == 4)   //保存旧的行列,另起一行
                        {
                            tableMain.Rows.Add(newrow);
                            intColspan = 0;
                            newrow = new TableRow();

                        }
                        TableCell newcellTitle = new TableCell(); //add title cell 
                        newcellTitle.ColumnSpan = 1;
                        Label labelTitle = new Label
                        {
                            Text = ReportProperty.Title,
                            SkinID = "LabelTitle",
                        };
                        newcellTitle.Controls.Add(labelTitle);
                        newrow.Cells.Add(newcellTitle);


                        TableCell newcellContent = new TableCell(); //add content cell

                        newcellContent.ColumnSpan = (ReportProperty.Colspan > 1 ? ReportProperty.Colspan - 1 : 1);
                        Label txtContent = new Label
                        {
                            ID = ReportProperty.PropertyName,
                        };
                        //CurrentControlClientIDList.Add(
                        //     new ManualItem()
                        //     {
                        //         Name = txtContent.ClientID,
                        //         Value = ReportProperty.PropertyId.ToString()
                        //     });

                        newcellContent.Controls.Add(txtContent);
                        newrow.Cells.Add(newcellContent);

                        intColspan += 2;
                    }

                    if (ReportProperty.PropertyType == DictionaryCategoryConst.GridColumnType.Calendar)
                    {
                        if (intColspan == 4 || ReportProperty.Colspan == 4)   //保存旧的行列,另起一行
                        {
                            tableMain.Rows.Add(newrow);
                            intColspan = 0;
                            newrow = new TableRow();
                        }
                        TableCell newcellTitle = new TableCell(); //add title cell

                        newcellTitle.ColumnSpan = 1;
                        Label labelTitle = new Label
                        {
                            Text = ReportProperty.Title,
                            SkinID = "LabelTitle",
                        };
                        newcellTitle.Controls.Add(labelTitle);
                        newrow.Cells.Add(newcellTitle);


                        TableCell newcellContent = new TableCell(); //add content cell

                        newcellContent.ColumnSpan = (ReportProperty.Colspan > 1 ? ReportProperty.Colspan - 1 : 1);
                        Label txtContent = new Label
                        {
                            ID = ReportProperty.PropertyName, 
                        }; 
                        newcellContent.Controls.Add(txtContent); 
                        newrow.Cells.Add(newcellContent);

                        intColspan += 2;
                    }

                    if (ReportProperty.PropertyType == DictionaryCategoryConst.GridColumnType.DictionaryItem)
                    {
                        if (intColspan == 4 || ReportProperty.Colspan == 4)   //保存旧的行列,另起一行
                        {
                            tableMain.Rows.Add(newrow);
                            intColspan = 0;
                            newrow = new TableRow();
                        }
                        TableCell newcellTitle = new TableCell(); //add title cell

                        newcellTitle.ColumnSpan = 1;
                        Label labelTitle = new Label
                        {
                            Text = ReportProperty.Title,
                            SkinID = "LabelTitle",
                        };
                        newcellTitle.Controls.Add(labelTitle);
                        newrow.Cells.Add(newcellTitle);


                        TableCell newcellContent = new TableCell(); //add content cell

                        newcellContent.ColumnSpan = (ReportProperty.Colspan > 1 ? ReportProperty.Colspan - 1 : 1);
                        Label txtContent = new Label
                        {
                            ID = ReportProperty.PropertyName,
                        };

                        newcellContent.Controls.Add(txtContent);
                        newrow.Cells.Add(newcellContent);
                        intColspan += 2;
                    }
                    if (intColspan > 0)
                    {
                        tableMain.Rows.Add(newrow);
                    }
                }
            }
        }


        private void LoadMonitor()
        {
            var entity = new ReportHeaderEntity(CurrentReportHeaderID);
            if (!entity.IsNew)
            {
          
                lblReportCode.Text = entity.ReportCode;
                BindReportValues(entity);
            }
        }
        private void BindReportValues(ReportHeaderEntity monitorEntity)
        {
            foreach (ReportValueEntity ReportValueEntity in monitorEntity.ReportValue)
            {
                if (ReportValueEntity.ReportProperty.PropertyType ==
                        DictionaryCategoryConst.GridColumnType.TextMode)
                {
                    var txtContent =
                        tableMain.FindControl(ReportValueEntity.ReportProperty.PropertyName) as Label;
                    if (txtContent != null)
                    {
                        txtContent.Text = ReportValueEntity.ReportValue;
                    }
                }

                if (ReportValueEntity.ReportProperty.PropertyType ==
                        DictionaryCategoryConst.GridColumnType.DictionaryItem)
                {
                    var dplContent =
                        tableMain.FindControl(ReportValueEntity.ReportProperty.PropertyName) as Label;
                    if (dplContent != null)
                    {
                        int intResult = 0;
                        if (int.TryParse(ReportValueEntity.ReportValue, out intResult))
                        {
                            dplContent.Text = GetDataName(intResult);
                        }

                    }
                }


                if (ReportValueEntity.ReportProperty.PropertyType ==
                        DictionaryCategoryConst.GridColumnType.Calendar)
                {
                    var txtContent =
                        tableMain.FindControl(ReportValueEntity.ReportProperty.PropertyName) as Label;
                    if (txtContent != null)
                    {
                        txtContent.Text = ReportValueEntity.ReportValue;
                    }
                }


                //if (ReportValueEntity.ReportProperty.PropertyType ==
                //        DictionaryCategoryConst.GridColumnType.RelativeTable)
                //{
                //    var dplContent =
                //        tableMain.FindControl(ReportValueEntity.ReportProperty.PropertyName) as DropDownList;
                //    if (dplContent != null)
                //    {
                //        dplContent.SelectedValue = ReportValueEntity.ReportValue;
                //    }
                //}

                //var txtComment1 =
                //    tableMain.FindControl(ReportValueEntity.ReportProperty.PropertyName + "Comment1") as TextBox;
                //var txtComment2 =
                //    tableMain.FindControl(ReportValueEntity.ReportProperty.PropertyName + "Comment2") as TextBox;

                //if (txtComment1 != null)
                //{
                //    txtComment1.Text = ReportValueEntity.Doc;
                //}

                //if (txtComment2 != null)
                //{
                //    txtComment2.Text = ReportValueEntity.Comment;
                //}
            }
        }

        private bool SaveMonitorProfile()
        {
            var reportCategory = new ReportCategoryEntity(CurrentReportCategoryID);
            var monitorEntity = new ReportHeaderEntity(CurrentReportHeaderID);
            bool boolIsNew = false;
            if (monitorEntity.IsNew)
            {
                monitorEntity.CreationUrl = reportCategory.CreationUrl + "?ReportHeaderID=" + monitorEntity.ReportHeaderId + "&ReportCategoryID=" + CurrentReportCategoryID;
                monitorEntity.ViewUrl = reportCategory.ViewUrl + "?ReportHeaderID=" + monitorEntity.ReportHeaderId + "&ReportCategoryID=" + CurrentReportCategoryID;
                monitorEntity.ReportCategoryId = CurrentReportCategoryID;
                monitorEntity.Status = DictionaryCategoryConst.ReportStatus.Saved;
                monitorEntity.TargetUserId = reportCategory.ApproveUserId;
                monitorEntity.ApplyUserId = CurrentLoginUser.UserID;
                monitorEntity.ReportCode = lblReportCode.Text;
                monitorEntity.ReportCategoryId = CurrentReportCategoryID;
                boolIsNew = true;
            }
            if (monitorEntity.Save())
            {
                if (boolIsNew)
                {
                    GlobalBusiness.UpdateReportCode();
                }
                return true;
            }
            return false;
        }


        private bool SaveReportValues(ReportHeaderEntity monitorEntity)
        {
            var collection = new ReportValueCollection();
            collection.DeleteMulti(ReportValueFields.ReportHeaderId == monitorEntity.ReportHeaderId);


            //针对每个ReportHeader property save 到这个monitor中
            foreach (ReportPropertyEntity ReportProperty in monitorEntity.ReportCategory.ReportProperty)
            {


                var ReportValueEntity = new ReportValueEntity();
                if (ReportProperty.PropertyType == DictionaryCategoryConst.GridColumnType.TextMode)
                {
                    var txtContent =
                        tableMain.FindControl(ReportProperty.PropertyName) as TextBox;
                    if (txtContent != null)
                    {
                        ReportValueEntity.ReportValue = txtContent.Text.Trim();
                    }
                }

                if (ReportProperty.PropertyType ==
                    DictionaryCategoryConst.GridColumnType.DictionaryItem)
                {
                    var dplContent =
                        tableMain.FindControl(ReportProperty.PropertyName) as DropDownList;
                    if (dplContent != null)
                    {
                        ReportValueEntity.ReportValue = dplContent.SelectedValue;
                    }
                }


                if (ReportProperty.PropertyType ==
                    DictionaryCategoryConst.GridColumnType.Calendar)
                {
                    var txtContent =
                        tableMain.FindControl(ReportProperty.PropertyName) as TextBox;
                    if (txtContent != null)
                    {
                        ReportValueEntity.ReportValue = txtContent.Text.Trim();
                    }
                }


                if (ReportProperty.PropertyType ==
                    DictionaryCategoryConst.GridColumnType.RelativeTable)
                {
                    var dplContent =
                        tableMain.FindControl(ReportProperty.PropertyName) as DropDownList;
                    if (dplContent != null)
                    {
                        ReportValueEntity.ReportValue = dplContent.SelectedValue;
                    }
                }

                ReportValueEntity.ReportHeaderId = monitorEntity.ReportHeaderId;
                ReportValueEntity.PropertyId = ReportProperty.PropertyId;

                ReportValueEntity.Save();

            }

            return true;
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {

            if (SaveMonitorProfile())
            {
                var monitorEntity = new ReportHeaderEntity(CurrentReportHeaderID);
                if (SaveReportValues(monitorEntity))
                {
                    RediretResolveUrl(SiteUrls.Report.MyReportHistory);
                }
            }
            else
            {
                Alert(GenerateAlert.SaveFailed);
            }
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            RediretResolveUrl(SiteUrls.Report.MyReportHistory);
        }
    }
}
